import { list, del, edit } from "../../api/index.js";
Page({
  data: {
    num: 0,
    noAddress: false,
    arr: [
      // {
      //   id: 0,
      //   name: "张三 先生",
      //   phone: "123456789",
      //   address: "万达广场1A158-159",
      // },
      // {
      //   id: 1,
      //   name: "美丽 女士",
      //   phone: "123412389",
      //   address: "万达广场1A174-320",
      // },
    ],
  },
  onLoad: function (options) {
    this.getlist();
  },
  onShow: function () {
    this.getlist();
  },
  async getlist() {
    const params = {
      pageNum: 1,
      pageSize: 100,
      userId: wx.getStorageSync("userInfo").userId,
    };
    const tableName = "address";
    const res = await list(params, tableName);
    if (res.code === 200) {
      const data = res.rows.map((item) => {
        return {
          id: item.id,
          name: item.receiptName,
          phone: item.phone,
          address: item.address,
          standby1: item.standby1,
        };
      });
      this.setData({
        arr: data,
      });
      console.log("data", data);
    }
  },
  async chooseAddress(e) {
    var type = e.currentTarget.dataset.id;
    this.data.arr.forEach(async (item) => {
      const params = { id: item.id, standby1: 0 };
      if (item.id === type) {
        params.standby1 = 1;
      }
      const res = await edit(params, "address");
      if (res.code === 200) {
        wx.showToast({
          title: "修改成功",
          icon: "success",
          duration: 2000,
        });
      }
    });
    this.getlist();
  },
  addAddress: function () {
    wx.navigateTo({
      url: "../addAddress/addAddress",
    });
  },
  async delAddress(e) {
    var that = this;
    var type = e.target.dataset.id;
    const res = await del(type, "address");
    if (res.code === 200) {
      wx.showToast({
        title: "删除成功",
        icon: "success",
        duration: 2000,
      });
    }
    wx.showModal({
      title: "提示",
      content: "确定删除该地址吗？",
      success: function (res) {
        if (res.confirm) {
          var index = that.data.num;
          var arr = that.data.arr;
          arr.splice(index, 1);
          that.setData({
            arr: arr,
          });
        }
      },
    });
  },
  toEdit: function (e) {
    var type = e.target.dataset.id;
    wx.navigateTo({
      url: "../addAddress/addAddress?id=" + type,
    });
  },
});
